package com.module.ble.widget

import android.annotation.SuppressLint
import android.content.Context
import android.os.CountDownTimer
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.common.app.databinding.ViewNumberChangeRoundBinding
import com.common.app.utls.Utils.px2sp
import com.common.base.app.extras.dpDimenPx
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils.getString
import com.module.ble.R
import com.module.ble.databinding.BleViewRingStateInfoBinding
import com.module.ble.listener.CusBleDeviceInfoExpandListener
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.utils.AizoSDKUtil


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：29/8/2023
 *
 * 描述：数字加减控件
 *
 * 修订历史：
 *
 */
class CusRingStateInfoView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr), View.OnClickListener,
    CusConnectBleDeviceExpandListener, CusBleDeviceInfoExpandListener {

    private val mViewBinding = BleViewRingStateInfoBinding.inflate(LayoutInflater.from(context), this, true)

    private var electricQuantity = ""

    private var mBtnCountDownTimer: CountDownTimer? = null

    private var mImageWidth = dpDimenPx(R.dimen.dp_30).toInt()
    private var mTextSize = 14

    private var lastPowerStateCheckTime = 0L
    private val POWER_STATE_CHECK_INTERVAL = 300000L // 5分钟间隔

    init {
        if (attrs != null) {
            initAttrs(context, attrs)
        }
        initView()
    }

    private fun initAttrs(context: Context, attributeSet: AttributeSet) {
        val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.ble_CusRingStateInfoView)
        mImageWidth = typedArray.getDimensionPixelSize(R.styleable.ble_CusRingStateInfoView_ble_ringstateinfo_img_size, mImageWidth)
        if (typedArray.hasValue(R.styleable.ble_CusRingStateInfoView_ble_ringstateinfo_img_size)) {
            mTextSize = typedArray.getDimension(R.styleable.ble_CusRingStateInfoView_ble_ringstateinfo_text_size, mTextSize.toFloat()).toInt()
            mTextSize = px2sp(context, mTextSize.toFloat())
        }
        typedArray.recycle()
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initView() {
        mViewBinding.ltRingLoading.layoutParams = LayoutParams(mImageWidth, mImageWidth)
        mViewBinding.imgRingState.layoutParams = LayoutParams(mImageWidth, mImageWidth)
        mViewBinding.ltRingPower.layoutParams = LayoutParams(mImageWidth, mImageWidth)
        mViewBinding.tvRingState.textSize = mTextSize.toFloat()
        mViewBinding.tvRingElectricQuantity.textSize = mTextSize.toFloat()
//        mViewBinding.numberChangeMinusBtn.setOnClickListener(onClick = this)
        AizoSDKUtil.addConnectBleDeviceExpandListener(this)
        AizoSDKUtil.addBleDeviceInfoExpandListener(this)
        electricQuantity = getString(R.string.common_rail_unit)
        onDevicePowerState(AizoSDKUtil.curElectricity, AizoSDKUtil.curWorkingMode)
    }


    override fun onClick(v: View) {
    }

    fun setElectricQuantity(){
        AizoSDKUtil.isConnect().yes {
            AizoSDKUtil.curRingInfoBean?.let {
                electricQuantity =  it.getRingElectricityStr()
            }
        }.otherwise {
            if(electricQuantity == "" || electricQuantity == "0") electricQuantity= "---"
        }

        mViewBinding.tvRingElectricQuantity.text = getString(R.string.common_ring_state_split, ("$electricQuantity${getString(R.string.common_bfb_unit)}"))
    }

    fun connectStateUi(mType: Int) {
        when (mType) {//0已断开1连接中2已连接
            1 -> {
                mViewBinding.imgRingState.visibility = View.VISIBLE
                mViewBinding.ltRingLoading.visibility = View.GONE
                mViewBinding.ltRingPower.visibility = View.VISIBLE
//                mViewBinding.ltRingLoading.pauseAnimation()
//                mViewBinding.ltRingLoading.resumeAnimation()
//                mViewBinding.ltRingLoading.imageAssetsFolder =
//                    "images"//设置data.json引用的图片资源文件夹名称,如果没有可不写
//                mViewBinding.ltRingLoading.setAnimation("loading.json")//通过AE生成的图文件(json格式)
//                mViewBinding.ltRingLoading.loop(true)//设置循环动画
//                mViewBinding.ltRingLoading.playAnimation()//开始动画
                mViewBinding.tvRingState.text = getString(R.string.common_ring_state_split, getString(R.string.common_ring_connecting_hint))
            }

            2 -> {
//                mViewBinding.imgRingState.setImageResource(R.drawable.ble_status_connected)
                mViewBinding.imgRingState.visibility = View.VISIBLE
                mViewBinding.ltRingLoading.visibility = View.GONE
                mViewBinding.ltRingPower.visibility = View.VISIBLE
                mViewBinding.tvRingState.text = getString(R.string.common_ring_state_split, getString(R.string.common_ring_connected_hint))
            }

            else -> {
//                mViewBinding.imgRingState.setImageResource(R.drawable.ble_status_disconnect)
                mViewBinding.imgRingState.visibility = View.VISIBLE
                mViewBinding.ltRingLoading.visibility = View.GONE
                mViewBinding.ltRingPower.visibility = View.VISIBLE
                mViewBinding.tvRingState.text = getString(R.string.common_ring_state_split, getString(R.string.common_ring_disconnected_hint))
            }
        }
    }

    override fun getVisibility(): Int {
        val isVisible = super.getVisibility()
        if (isVisible == VISIBLE) {
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastPowerStateCheckTime > POWER_STATE_CHECK_INTERVAL) {//确保 getVisibility() 方法不会在短时间内被多次调用，提高应用性能。
                AizoSDKUtil.getDevicePowerState()
                lastPowerStateCheckTime = currentTime
            }
        }
        return isVisible
    }

    override fun onConnect(macStr: String?) {
        connectStateUi(2)
        setElectricQuantity()
    }

    override fun onConnectError(macStr: String?, throwable: Throwable?, state: Int) {
        createConnectCountDownTimer()
    }

    override fun onDisconnect(macStr: String?) {
        createConnectCountDownTimer()
    }

    override fun onDevicePowerState(electricity: String, workingMode: Int) {//0未充电1充电中other未充电
        setElectricQuantity()
        (workingMode == 1).yes {
//            mViewBinding.imgRingState.visibility = View.GONE
            mViewBinding.ltRingPower.visibility = View.GONE
            mViewBinding.ltRingLoading.visibility = View.VISIBLE
            mViewBinding.ltRingLoading.pauseAnimation()
            mViewBinding.ltRingLoading.resumeAnimation()
            mViewBinding.ltRingLoading.imageAssetsFolder = "images"//设置data.json引用的图片资源文件夹名称,如果没有可不写
            mViewBinding.ltRingLoading.setAnimation("ble_animation_charging.json")//通过AE生成的图文件(json格式)
            mViewBinding.ltRingLoading.loop(true)//设置循环动画
            mViewBinding.ltRingLoading.playAnimation()//开始动画
        }.otherwise {
            connectStateUi(AizoSDKUtil.isConnect)
        }
    }

    override fun onGetDeviceInfo() {
    }

    override fun onHandleDevice(type: Int, result: Boolean) {
        connectStateUi(AizoSDKUtil.isConnect)
    }

    override fun onBoundDeviceResult(macStr: String, result: Boolean) {
    }

    override fun onDetachedFromWindow() {
        AizoSDKUtil.removeConnectBleDeviceExpandListener(this)
        AizoSDKUtil.removeBleDeviceInfoExpandListener(this)
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer = null
        super.onDetachedFromWindow()
    }

    private fun createConnectCountDownTimer() {
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer = null
        mBtnCountDownTimer = object : CountDownTimer(30, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                connectStateUi(AizoSDKUtil.isConnect)
            }
        }
        mBtnCountDownTimer?.start()
        connectStateUi(1)
    }
}
